#! /bin/sh
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#  KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#

set -e

CORDOVA_PATH=$( cd "$( dirname "$0" )" && pwd )
PROJECT_PATH=$CORDOVA_PATH/..

function getAppPath() {
	for file in "$( find "$PROJECT_PATH" -type d -name '*.xcodeproj' | sort )"; do
	  PROJECT_NAME=$(basename "$file" .xcodeproj)
	done;
	APP=build/$PROJECT_NAME.app
	APP_PATH="$PROJECT_PATH/$APP"
}

APP_PATH=$1

if [ $# -lt 1 ]; then
	getAppPath
fi

if [ ! -d "$APP_PATH" ]; then
	read -p "Project '$APP_PATH' is not built. Build? [y/n]: " REPLY 
	if [ "$REPLY" == "y" ]; then 
		$CORDOVA_PATH/debug
		exit 0
	else 
		echo "$APP_PATH not found to emulate."
		exit 1
	fi	
fi

# launch using ios-sim

if which ios-sim >/dev/null; then
    ios-sim launch "$APP_PATH" --stderr "$CORDOVA_PATH/console.log" --stdout "$CORDOVA_PATH/console.log" &
else
    echo -e '\033[31mError: ios-sim was not found. Please download, build and install version 1.4 or greater from https://github.com/phonegap/ios-sim into your path. Or "brew install ios-sim" using homebrew: http://mxcl.github.com/homebrew/\033[m'; exit 1;
fi

